//
//  CreatePatientMainViewController.m
//  StraightTrain
//
//  Created by mk on 15/11/26.
//  Copyright (c) 2015年 mk. All rights reserved.
//

#import "CreatePatientMainViewController.h"
#import "PatientMedicalRecordViewController.h"

@interface CreatePatientMainViewController ()
{
    BOOL showCityPick;//显示城市
    UITextField * textNow;//当前响应的text
    NSString * selectGenderID;//性别id
    int keyHeight;

}

@end

@implementation CreatePatientMainViewController

-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                        selector:@selector(keyboardWillShow:)
                                                 name:UIKeyboardWillShowNotification
                                               object:nil];
}


-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [self clearView];
    [[NSNotificationCenter defaultCenter] removeObserver:self
                                                    name:UIKeyboardWillShowNotification
                                                  object:nil];
}

#pragma mark 创建城市pick
-(void)createCityPicker
{
    if (!pickCity)
    {
        pickCity = [[CityPickView alloc] init];
        pickCity.selectDelegate = self;
        pickCity.backgroundColor = [UIColor whiteColor];
        [pickCity setTranslatesAutoresizingMaskIntoConstraints:NO];
        [self.view addSubview:pickCity];
        NSDictionary *views = NSDictionaryOfVariableBindings(pickCity);
        [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-0@1000-[pickCity]-0@1000-|"
                                                                          options:0
                                                                          metrics:nil
                                                                            views:views]];
        
        NSLayoutConstraint *constraintHE = [NSLayoutConstraint constraintWithItem:self.view
                                                                        attribute:NSLayoutAttributeBottom
                                                                        relatedBy:NSLayoutRelationEqual
                                                                           toItem:pickCity
                                                                        attribute:NSLayoutAttributeBottom
                                                                       multiplier:1
                                                                         constant:-202];
        [self.view addConstraint:constraintHE];
        
        NSLayoutConstraint *constraintV = [NSLayoutConstraint constraintWithItem:pickCity
                                                                       attribute:NSLayoutAttributeHeight
                                                                       relatedBy:NSLayoutRelationEqual
                                                                          toItem:nil
                                                                       attribute:NSLayoutAttributeHeight
                                                                      multiplier:1
                                                                        constant:202];
        [self.view addConstraint:constraintV];
    }
    
}




- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    [scrollMain setAlwaysBounceVertical:YES];
  
    titleLabel.text = @"创建患者";
    
    for(UIImageView * imageBG in [viewMain subviews])
    {
        if (imageBG.tag>=100)
        {
            [imageBG setImage:[[UIImage imageNamed:@"default_text_wither_bg.png"] stretchableImageWithLeftCapWidth:20 topCapHeight:20]];
        }
    }
    
    //性别
   
    NSArray * arrGenderK = [gProjConfig.dicGender allKeys];
    NSArray * arrGenderV = [gProjConfig.dicGender allValues];
    [btnnam setTitle:[arrGenderV objectAtIndex:0] forState:UIControlStateNormal];
    btnnam.tag = [[arrGenderK objectAtIndex:0] integerValue];
    [btnnv setTitle:[arrGenderV objectAtIndex:1] forState:UIControlStateNormal];
    btnnv.tag = [[arrGenderK objectAtIndex:1] integerValue];
    selectGenderID = @"-1";//默认
  
    //datePick
    [pickTime setMaximumDate:[NSDate new]];
    [pickTime setBackgroundColor:[UIColor whiteColor]];
    [pickTime setDate:[NSDate date] animated:NO];
    [pickTime setDatePickerMode:UIDatePickerModeDate];
    labTimeTitle.text = [CommonFunctions convertDate:[NSDate date] withFormatter:@"yyyy-MM" subFromIndex:0];
    
    //City
   
    NSMutableDictionary * dicProvince = [gProjConfig.arrCity objectAtIndex:pickCity.selectProvince];
    NSString * strProvince = [dicProvince objectForKey:@"state"];
        //市
    NSMutableArray * arrayCity = [dicProvince objectForKey:@"subCity"];
    NSMutableDictionary * dicCity = [arrayCity objectAtIndex:pickCity.selectCity];
    NSString * strCity = [dicCity objectForKey:@"city"];
    if ([strCity isEqualToString:strProvince])
    {
        labCity.text = [NSString stringWithFormat:@"%@市",strCity];
    }else
    {
        labCity.text = [NSString stringWithFormat:@"%@省/%@市",strProvince,strCity];
    }
   
    
     labTime.text = [CommonFunctions convertDate:[NSDate new] withFormatter:@"yyyy-MM" subFromIndex:0];

    [self createCityPicker];
    pickCity.cityTitle.text = labCity.text;
}

#pragma mark 选择性别
-(IBAction)selectGender:(id)sender
{
    [self showdatePick:NO];
    [self showCityPickerData:NO];
    [textNow resignFirstResponder];
    [tevDiseaseDescription resignFirstResponder];
    
    UIButton * btn = (UIButton *)sender;
    if (btn == btnnam)
    {
        [btnnam setImage:[UIImage imageNamed:@"default_select_btn_off.png"] forState:UIControlStateNormal];
        [btnnv setImage:[UIImage imageNamed:@"default_select_btn_on.png"] forState:UIControlStateNormal];
    }else
    {
        [btnnam setImage:[UIImage imageNamed:@"default_select_btn_on.png"] forState:UIControlStateNormal];
        [btnnv setImage:[UIImage imageNamed:@"default_select_btn_off.png"] forState:UIControlStateNormal];
    }

    selectGenderID = [NSString stringWithFormat:@"%ld",(long)btn.tag];
    
}

#pragma mark 选择时间
-(IBAction)selectTime:(id)sender
{
    [self showdatePick:YES];
    [self showCityPickerData:NO];
    [textNow resignFirstResponder];
    [tevDiseaseDescription resignFirstResponder];
}

#pragma mark 确定选择时间
-(IBAction)selectTimeOK:(id)sender
{
    labTime.text = labTimeTitle.text;
   [self showdatePick:NO];
}

#pragma mark 取消选择时间
-(IBAction)selectTimeNO:(id)sender
{
   [self showdatePick:NO];
}

-(IBAction)timeValueChange
{
  labTimeTitle.text = [CommonFunctions convertDate:pickTime.date withFormatter:@"yyyy-MM" subFromIndex:0];
}

#pragma mark 选择城市
-(IBAction)selectCity:(id)sender
{
    [self showdatePick:NO];
    [self showCityPickerData:YES];
    [textNow resignFirstResponder];
    [tevDiseaseDescription resignFirstResponder];
}

#pragma marl cityPickView

-(void)citytoolBarDoneClick:(id)sender
{
    labCity.text = pickCity.cityTitle.text;
}


-(IBAction)btnNext:(id)sender
{
    
    [self showdatePick:NO];
    [self showCityPickerData:NO];
    [textNow resignFirstResponder];
    [tevDiseaseDescription resignFirstResponder];
    [scrollMain setContentOffset:CGPointMake(0,0) animated:YES];
    
    NSString * strTel = TextNsString(textTel.text)
    NSString * strName = TextNsString(textName.text)
    NSString * strDiseaseName = TextNsString(textDiseaseName.text)
    NSString * strDiseaseDescription = TextNsString(tevDiseaseDescription.text)
    
    if(strName.length==0)
    {
      Alert(alerTitle, @"请填写患者姓名", @"确定")
        return;
    }
    if(strTel.length==0)
    {
        Alert(alerTitle, @"请填写患者的联系方式", @"确定")
        return;
    }else
    {
        //电话类型
        NSRegularExpression *regex2 = [NSRegularExpression regularExpressionWithPattern:@"^[0-9]*$" options:0 error:nil];
        if (regex2)
        {
            NSTextCheckingResult *result2 = [regex2 firstMatchInString:strTel options:0 range:NSMakeRange(0, [strTel length])];
            if (!result2)
            {
                Alert(alerTitle, @"请填写纯数字类型联系方式", @"确定")
                return;
            }
        }
        
        //最小电话长度
        if(strTel.length<7)
        {
            Alert(alerTitle, @"请填写正确的联系方式", @"确定")
            return;
        }
    }
    if([selectGenderID isEqualToString:@"-1"])
    {
        Alert(alerTitle, @"请选择患者的性别", @"确定")
        return;
    }
    
    if(strDiseaseName.length==0)
    {
        Alert(alerTitle, @"请填写患者的疾病名称", @"确定")
        return;
    }
    if(strDiseaseDescription.length==0)
    {
        Alert(alerTitle, @"请填写疾病描述", @"确定")
        return;
    }
    if(labTime.text.length==0)
    {
        Alert(alerTitle, @"请选择患者的出生年月", @"确定")
        return;
    }
        NSMutableDictionary * dicData = [[NSMutableDictionary alloc]initWithCapacity:0];
        
        [dicData setObject:[gProjConfig.dicUserData objectForKey:USER_tel] forKey:@"patient[username]"];
        [dicData setObject:[gProjConfig.dicUserData objectForKey:USER_token] forKey:@"patient[token]"];
        [dicData setObject:strTel forKey:@"patient[mobile]"];
        [dicData setObject:strName forKey:@"patient[name]"];
        [dicData setObject:strDiseaseName forKey:@"patient[disease_name]"];
        [dicData setObject:strDiseaseDescription forKey:@"patient[disease_detail]"];
        
        //省
        NSMutableDictionary * dicProvince = [gProjConfig.arrCity objectAtIndex:pickCity.selectProvince];
        NSString * strProvinceID = [dicProvince objectForKey:@"id"];
        //市
        NSMutableArray * arrayCity = [dicProvince objectForKey:@"subCity"];
        NSMutableDictionary * dicCity = [arrayCity objectAtIndex:pickCity.selectCity];
        NSString * strCityID = [dicCity objectForKey:@"id"];
        
        [dicData setObject:strProvinceID forKey:@"patient[state_id]"];//省
        [dicData setObject:strCityID forKey:@"patient[city_id]"];//市
        [dicData setObject:selectGenderID forKey:@"patient[gender]"];
        [dicData setObject:labTime.text forKey:@"patient[birth]"];
       
        SetHUDStartText(@"提交信息..")
    
         NSString * strUrl = NullObjToString([gProjConfig.dicAllUrl objectForKey:@"createPatientUrl"]);
        [[HttpClient manager]POST:strUrl
                                 parameters:dicData
            success:^(AFHTTPRequestOperation *operation, id responseObject)
            {
                SetHUDHidden;
                PatientMedicalRecordViewController * record = [[PatientMedicalRecordViewController alloc]initWithNibName:@"PatientMedicalRecordViewController" bundle:nil];
                record.strID = NullObjToString([[responseObject objectForKey:requestDataKey] objectForKey:@"id"]);
                record.strType = @"mr";//病例
                [self.navigationController pushViewController:record animated:YES];
                
                //消除这个页面,保证在最后详情界面可直接跳转到首页
                NSMutableArray * array =[[NSMutableArray alloc]initWithArray:self.navigationController.viewControllers];
                [array removeObjectAtIndex:array.count-2];
                self.navigationController.viewControllers = array;
            }
            failure:^(AFHTTPRequestOperation *operation, NSError *error)
             {
                 SetHUDHidden;
               HUDShowRequestError(error.domain, self.view)
            }];
    
}



#pragma mark showDataView
-(void)showCityPickerData:(BOOL)show
{
    for (NSLayoutConstraint *constraints in [pickCity.superview constraints])
    {
        if (constraints.firstItem == self.view && constraints.secondItem == pickCity && constraints.firstAttribute == NSLayoutAttributeBottom && constraints.secondAttribute == NSLayoutAttributeBottom)
        {
            [UIView animateWithDuration:0.2 animations:^
            {
                constraints.constant = (show?0:-202);
                [self.view layoutIfNeeded];
            } completion:^(BOOL finished)
             {
             }];
            break;
        }
    }
    
}


#pragma mark 隐藏显示日期view
-(void)showdatePick:(BOOL)showDate
{
    for (NSLayoutConstraint * constraints in [viewAllPick.superview constraints])
    {
        if (constraints.firstItem == viewAllPick.superview && constraints.firstAttribute == NSLayoutAttributeBottom && constraints.secondItem == viewAllPick && constraints.secondAttribute == NSLayoutAttributeBottom)
        {
            [UIView animateWithDuration:0.2 animations:^
             {
                 constraints.constant = (showDate?0:-202);
                 [self.view layoutIfNeeded];
             }];
            break;
        }
    }
    
}


#pragma mark textFieldDelegate
-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return YES;
}


-(BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
    [self showdatePick:NO];
    [self showCityPickerData:NO];
    
    textNow = textField;
    [self changeViewFrame];
    
    return YES;
}

-(void)textFieldDidEndEditing:(UITextField *)textField
{
    [scrollMain setContentOffset:CGPointMake(0,0) animated:YES];
}

-(void)textViewDidBeginEditing:(UITextView *)textView
{
    [self showdatePick:NO];
    [self showCityPickerData:NO];
    textNow = nil;
    [self changeViewFrame];
}

-(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    if ([text isEqualToString:@"\n"])
    {
        [tevDiseaseDescription resignFirstResponder];
        [scrollMain setContentOffset:CGPointMake(0,0) animated:YES];
        return NO;
    }
    return YES;
}


#pragma mark //当键盘出现或改变时调用
- (void)keyboardWillShow:(NSNotification *)aNotification
{
    //获取键盘的高度
    NSDictionary *userInfo = [aNotification userInfo];
    NSValue *aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect keyboardRect = [aValue CGRectValue];
    keyHeight = keyboardRect.size.height;
    
    [self changeViewFrame];
}

-(void)changeViewFrame
{
    int bottomDistance;
    if (textNow == nil)
    {
        bottomDistance = appScreenHeight -  tevDiseaseDescription.bottom-64;//键盘预留高度
    }else
    {
        bottomDistance = appScreenHeight - textNow.bottom-64;//键盘预留高度
    }
    
    int content = bottomDistance - (keyHeight + 30);//键盘到text得间距
    
    if (content < 0)
    {
        [scrollMain setContentOffset:CGPointMake(0,-content) animated:YES];
    }
}


- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    [tevDiseaseDescription resignFirstResponder];
    [textNow resignFirstResponder];
    
    [self showdatePick:NO];
}

-(IBAction)clearView
{
    [tevDiseaseDescription resignFirstResponder];
    [textNow resignFirstResponder];
    [self showCityPickerData:NO];
    [self showdatePick:NO];
    [scrollMain setContentOffset:CGPointMake(0,0) animated:NO];
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
